package com.kye.express.business.service.popup;

import android.animation.Animator;
import android.animation.Animator.AnimatorListener;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;

import com.kye.express.R;
import com.kye.express.business.jd_reservation.list.JdReservationListActivity;
import com.kye.express.business.networkpoint_query.NetworkPointQueryActivity;
import com.kye.express.business.waybill_take_photo.WaybillTakePhotoActivity;
import com.kye.express.business.web.KyeWebActivity;
import com.kye.express.config.KyeResAction;

/**
 * 点击寄件的PopupWindow菜单弹出效果
 * <p>
 * Source http://blog.csdn.net/u011624883/article/details/50522722
 * Created by SkyYu on 2018/2/11
 */
public class MoreWindow extends PopupWindow implements OnClickListener {

    private String TAG = MoreWindow.class.getSimpleName();
    private int statusBarHeight;
    private Activity mContext;
    private Bitmap mBitmap = null;
    private Bitmap overlay = null;

    private OnClickListener mOnClickAddOrderListener;

    private Handler mHandler = new Handler();

    public MoreWindow(Activity context) {
        mContext = context;
    }

    public void init() {
        Rect frame = new Rect();
        mContext.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        statusBarHeight = frame.top;

        DisplayMetrics metrics = new DisplayMetrics();
        mContext.getWindowManager().getDefaultDisplay().getMetrics(metrics);
        setWidth(metrics.widthPixels);
        setHeight(metrics.heightPixels);
    }

    public void destroy() {
        if (null != overlay && !overlay.isRecycled()) {
            overlay.recycle();
            overlay = null;
        }
        if (null != mBitmap && !mBitmap.isRecycled()) {
            mBitmap.recycle();
            mBitmap = null;
        }
        System.gc();
    }

    private Bitmap blur() {
        if (null != overlay) {
            return overlay;
        }
        long startMs = System.currentTimeMillis();

        View view = mContext.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache(true);
        mBitmap = view.getDrawingCache();

        float scaleFactor = 8;
        float radius = 10;
        int width = mBitmap.getWidth();
        int height = mBitmap.getHeight();

        overlay = Bitmap.createBitmap((int) (width / scaleFactor), (int) (height / scaleFactor), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(overlay);
        canvas.scale(1 / scaleFactor, 1 / scaleFactor);
        Paint paint = new Paint();
        paint.setFlags(Paint.FILTER_BITMAP_FLAG);
        canvas.drawBitmap(mBitmap, 0, 0, paint);

        overlay = FastBlur.doBlur(overlay, (int) radius, true);
        Log.i(TAG, "blur time is:" + (System.currentTimeMillis() - startMs));
        return overlay;
    }

    public void showMoreWindow(View anchor) {
        final RelativeLayout layout = (RelativeLayout) LayoutInflater.from(mContext).inflate(R.layout.window_service, null);
        setContentView(layout);

        showAnimation(layout);
        setBackgroundDrawable(new BitmapDrawable(mContext.getResources(), blur()));
        setOutsideTouchable(true);
        setFocusable(true);
        showAtLocation(anchor, Gravity.BOTTOM, 0, statusBarHeight);

        for (int i = 0; i < layout.getChildCount() - 1; i++) {
            final LinearLayout parent = (LinearLayout) layout.getChildAt(i);
            for (int j = 0; j < parent.getChildCount(); j++) {
                parent.getChildAt(j).setOnClickListener(this);
            }
        }

        ImageView close = layout.findViewById(R.id.imageview_service_exit);
        close.setOnClickListener(view -> {
            if (isShowing()) {
                closeAnimation(layout);
            }
        });
    }

    private Animation showAnimation(final View view, int fromY, int toY) {
        AnimationSet set = new AnimationSet(true);
        TranslateAnimation go = new TranslateAnimation(0, 0, fromY, toY);
        go.setDuration(300);
        TranslateAnimation go1 = new TranslateAnimation(0, 0, -10, 2);
        go1.setDuration(100);
        go1.setStartOffset(250);
        set.addAnimation(go1);
        set.addAnimation(go);

        set.setAnimationListener(new AnimationListener() {
            @Override
            public void onAnimationEnd(Animation animation) {
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }

            @Override
            public void onAnimationStart(Animation animation) {

            }

        });
        return set;
    }

    private void showAnimation(ViewGroup layout) {
        for (int i = 0; i < layout.getChildCount(); i++) {
            final View child = layout.getChildAt(i);
            if (child.getId() == R.id.imageview_service_exit) {
                continue;
            }
            child.setVisibility(View.INVISIBLE);
            mHandler.postDelayed(() -> {
                child.setVisibility(View.VISIBLE);
                ValueAnimator fadeAnim = ObjectAnimator.ofFloat(child, "translationY", 600, 0);
                fadeAnim.setDuration(300);
                KickBackAnimator kickAnimator = new KickBackAnimator();
                kickAnimator.setDuration(150);
                fadeAnim.setEvaluator(kickAnimator);
                fadeAnim.start();
            }, i * 50);
        }
    }

    private void closeAnimation(ViewGroup layout) {
        for (int i = 0; i < layout.getChildCount(); i++) {
            final View child = layout.getChildAt(i);
            if (child.getId() == R.id.imageview_service_exit) {
                continue;
            }
            child.setOnClickListener(this);
            mHandler.postDelayed(() -> {
                child.setVisibility(View.VISIBLE);
                ValueAnimator fadeAnim = ObjectAnimator.ofFloat(child, "translationY", 0, 600);
                fadeAnim.setDuration(200);
                KickBackAnimator kickAnimator = new KickBackAnimator();
                kickAnimator.setDuration(100);
                fadeAnim.setEvaluator(kickAnimator);
                fadeAnim.start();
                fadeAnim.addListener(new AnimatorListener() {
                    @Override
                    public void onAnimationStart(Animator animation) {

                    }

                    @Override
                    public void onAnimationRepeat(Animator animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animator animation) {
                        child.setVisibility(View.INVISIBLE);
                        dismiss();
                    }

                    @Override
                    public void onAnimationCancel(Animator animation) {

                    }
                });
            }, (layout.getChildCount() - i - 1) * 30);

            if (child.getId() == R.id.linearlayout_service_addorder) {
                mHandler.postDelayed(() ->
                        dismiss(), (layout.getChildCount() - i) * 30 + 80
                );
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.linearlayout_service_addorder:
                if (mOnClickAddOrderListener != null) mOnClickAddOrderListener.onClick(v);
                break;
            case R.id.linearlayout_service_waybillphotogragh:
                WaybillTakePhotoActivity.startActivity(mContext);
                break;
            case R.id.linearlayout_service_networkquery:
                NetworkPointQueryActivity.startActivity(mContext);
                break;
            case R.id.linearlayout_service_aviationcontraband:
                KyeWebActivity.startActivity(mContext, KyeResAction.AVIATION_CONTRABAND, mContext.getString(R.string.aviation_contraband), false);
                break;
            case R.id.linearlayout_service_jdorder:
                JdReservationListActivity.startActivity(mContext);
                break;
            default:
                break;
        }
    }

    public OnClickListener getOnClickAddOrderListener() {
        return mOnClickAddOrderListener;
    }

    public void setOnClickAddOrderListener(OnClickListener onClickAddOrderListener) {
        mOnClickAddOrderListener = onClickAddOrderListener;
    }
}